package Server.service.impl;

import Server.dao.RequestLogDao;
import Server.entity.RequestLog;
import Server.entity.Users;
import Server.service.LogService;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Service
public class LogServiceImpl implements LogService {
    @Autowired
    private RequestLogDao requestLogDao;
    @Override
    public void LoginLog(HttpServletRequest request, RequestLog.Status status) {
        String ret = (String) SecurityUtils.getSubject().getSession().getAttribute("ret");
        if(status.equals(RequestLog.Status.YES)){
            Users users = (Users) SecurityUtils.getSubject().getSession().getAttribute("Users");
            RequestLog sysLog = new RequestLog();
            sysLog.setApiName("登录");
            sysLog.setJsJson(users.getName());
            sysLog.setIp(request.getHeader("X-real-ip"));
            sysLog.setFhJson("成功");
            sysLog.setStatus(status);
            Enumeration er = request.getHeaderNames();
            StringBuilder herder = new StringBuilder();
            while (er.hasMoreElements()) {
                String name = (String) er.nextElement();
                String value = request.getHeader(name);
                herder.append("  " + name + "=" + value);
            }
            sysLog.setHeaders(herder.toString());
            requestLogDao.save(sysLog);
        } else{
            RequestLog sysLog = new RequestLog();
            sysLog.setApiName("登录");
            sysLog.setJsJson(ret);
            sysLog.setIp(request.getHeader("X-real-ip"));
            sysLog.setFhJson("失败");
            sysLog.setStatus(status);
            Enumeration er = request.getHeaderNames();
            StringBuilder herder = new StringBuilder();
            while (er.hasMoreElements()) {
                String name = (String) er.nextElement();
                String value = request.getHeader(name);
                herder.append("  " + name + "=" + value);
            }
            sysLog.setHeaders(herder.toString());
            requestLogDao.save(sysLog);
        }
    }
    @Override
    public void logSave(RequestLog requestLog) {
        requestLogDao.save(requestLog);
    }
}
